// components/search/index.js

import {KeywordModel} from '../../models/keyword.js'
import {BookModel} from '../../models/book.js'
import {paginationBev} from '../behaviors/pagination.js'

const keywordModel = new KeywordModel()
const bookModel = new BookModel()
Component({
  /**
   * 组件的属性列表
   */
  
  behaviors: [paginationBev],
  properties: {
    getMore: {
      type:String,
      observer: 'loadMore'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hotWords: [],
    // dataArray: [],
    searchBegin: false,
    inputValue: '',
    loading: false,
    loadingCenter: false,
    loadingBottom: false
  },

  attached(){
    this.setData({
      historyWords: keywordModel.getHistory()
    })

    keywordModel.getHot().then((res) => {
      this.setData({
        hotWords: res.hot
      })
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    loadMore(){
      this.setData({
        loadingBottom: true
      })
      /* 当用户翻页到最底部时，向服务器发送请求加载更多书箱信息 
      第一次获取20条数据存入dataArray，那么两次获取时的起始数就是dataArray数组目前的长度
      将两次获取的数组合并成一组再重新赋值给dataArray */
      // const lentgh = this.data.dataArray.length
      if (!this.data.inputValue) {return}

      if (!this.data.loading && this.hasMore()) {
        this.setData({
          loading: true
        })
        bookModel.search(this.getCurrentStart(), this.data.inputValue)
        .then(res => {
          this.setMoreData(res.books)
          // const tempArray = this.data.dataArray.concat(res.books)
          // this.setData({
          //   dataArray: tempArray
          // })
          this.setData({
            loading: false
          })
        }, ()=>{
          this.setData({
            loading: false
          })
        })
      }
    },

    cancelSearch(event) {
      /* body... */
      this.empty()
      this.triggerEvent('cancel')
    },
    cancelSearchResult(event){
      this.empty()
      this.setData({
        searchBegin: false,
        inputValue: ''
      })
    },

    onConfirm(event){
      // 获取用户在搜索框中输入的内容
      const word = event.detail.value || event.detail.content
      // wx.showLoading({
      //   title: '图书加载中'
      // })
      this.setData({
        searchBegin: true,
        inputValue: word,
        loadingCenter: true
        // dataArray: []
      })
      this.empty()

      bookModel.search(0, word).then(res => {
        this.setMoreData(res.books)
        this.setTotal(res.total)
        keywordModel.addToHistory(word)
        this.setData({
          loadingCenter: false
        })
      })
    }
  }
})
